package com.lw.leetcode.dp.b;

/**
 * Created with IntelliJ IDEA.
 * 32. 最长有效括号
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/13 13:14
 */
public class LongestValidParentheses {
    public int longestValidParentheses(String s) {
        int length = s.length();
        if (length < 2) {
            return 0;
        }
        int[] dp = new int[length];
        int max = 0;
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == '(') {
                dp[i] = 1;
            } else {
                int l = i - 1 >= 0 ? dp[i - 1] : 0;
                int ll = i - l - 1 >= 0 ? dp[i - l - 1] : 0;
                if (l > 1) {
                    if (ll == 1) {
                        dp[i] = l + 2;
                        ll = i - l - 2 >= 0 ? dp[i - l - 2] : 0;
                    }
                } else if (l == 1) {
                    dp[i] = 2;
                }
                if (l > 0 && (ll & 1) == 0) {
                    dp[i] += ll;
                }
            }
            if (dp[i] > max && dp[i] != 1) {
                max = dp[i];
            }
        }
        return max;
    }
}
